<template>
    <div class="head">
        <div class="square" v-if="!router.currentRoute.value.query.type">
            <div class="left all" @click="backpage">
                <el-icon><ArrowLeftBold /></el-icon>
                <span class="fontstyle" style="margin-right: 12px">退出编辑器</span>
            </div>

            <div class="right all">
                <div class="all space hove">
                    <el-button @click="preview" :icon="View">预览</el-button>
                </div>
                <div class="all space hove" v-if="form.data.status != 1">
                    <el-button @click="submit(2)" :icon="SuccessFilled">保存</el-button>
                </div>
                <el-button type="primary" @click="publish" :icon="Promotion">发布</el-button>
            </div>
        </div>
        <div class="head-preview" v-if="router.currentRoute.value.query.type">
            <el-button type="primary" @click="closePage">关闭</el-button>
        </div>
    </div>
    <div class="container">
        <Left @drag="dragHandler" @drag-end="dragEndHandler" v-if="!router.currentRoute.value.query.type"></Left>
        <div class="center" ref="centerRef">
            <div class="preview" :style="{ height: totalHeight + 'px' }">
                <div
                    v-if="visible"
                    ref="previewRef"
                    class="iframe-mask"
                    :style="{ minHeight: maskHeight + 'px' }"
                    @dragenter="dragenterHandler"
                    @dragleave="dragleaveHandler"
                    @dragover="dragoverHandler"
                    @drop="dropHandler">
                    <div
                        :ref="el => setItemRef(el, index)"
                        @dragover="dragoverItemHandler($event, index)"
                        class="iframe-mask-item"
                        v-for="(item, index) in iframeHeightArr"
                        :key="index"
                        :style="{ height: item + 'px', zIndex: 9999 }">
                        {{ index }}
                    </div>
                </div>
                <div class="preview-mask" v-if="visible" :style="{ height: totalHeight + 'px' }"></div>
                <iframe
                    class="iframe-win"
                    :title="pageInfo.title"
                    :src="pageInfo.previewUrl"
                    frameBorder="0"
                    :allowTransparency="true"
                    :allowFullScreen="true"
                    ref="iframeRef"
                    width="100%"
                    scrolling="no"
                    :height="totalHeight" />
            </div>
        </div>
        <div class="code-contail" v-if="router.currentRoute.value.query.type">
            <div class="head-text">手机预览</div>
            <div class="head-contail">
                <el-image
                    title="点击预览"
                    placeholder="加载中..."
                    class="head-code"
                    :src="previewUrl"
                    :preview-teleported="true"
                    :preview-src-list="[previewUrl]"
                    fit="cover">
                    <template #error>
                        <div class="head-err">加载中...</div>
                    </template>
                </el-image>
                <div class="head-tips">微信扫码预览</div>
            </div>
        </div>
        <Right
            v-if="!router.currentRoute.value.query.type"
            @changeOptions="changeOptionsHandler"
            :type="name"
            :comIndex="comIndex"
            :form="form.data"
            :components="components"></Right>
    </div>
</template>
<script setup>
import { Promotion, SuccessFilled, View } from '@element-plus/icons-vue';
import { reactive, ref, nextTick, watch, onMounted, onBeforeUnmount, onUnmounted } from 'vue';
import storage from '@/commons/storage';
import { getMiniAppQrcodeHook } from '@/hooks';
import IframeMessage from '@/commons/iframeMessage';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import ElemBox from '@/commons/element/message.js';
import { isEmpty, getPreviewUrl } from '@/commons/utils';
import QrcodeVue from 'qrcode.vue';
import Left from './comlist.vue';
import Right from './options/index.vue';
import request from '@/request';

const router = useRouter();
const iframeRef = ref(null);
const previewRef = ref(null);
const centerRef = ref(null);
let iframeHeightArr = reactive([]);
let totalMixHeight = 887;
let totalHeight = ref(totalMixHeight);
let maskHeight = ref(627);
let iframeMessage;
let comIndex = ref(0);
let components = ref([]);
const nowAbove = reactive({
    index: -1,
    status: ''
});
let form = reactive({ data: {} });
const name = ref('info');
let previewUrl = ref();
let currentDragComponent;
let visible = ref(false);
let id = ref();
const maskRefs = {};
//区分保存和预览操作1预览 2保存 3 发布
let isPreview = ref(2);
//是否进行了保存操作
let isSave = ref(false);
//是否进行删除、上移、下移组件内容（true：是，false：否）
let isOperate = ref(false);
//防抖：避免点击保存多次
let oneSave = ref(false);
let infotips = reactive({
    templateName: '页面名称',
    templateDesc: '页面说明',
    shareImg: '分享图片',
    shareTitle: '分享标题',
    isHomePage: '2'
});
const setItemRef = (el, index) => {
    if (el) {
        maskRefs[index] = el;
    }
};
const pageInfo = reactive({
    title: 'h5',
    previewUrl: `${import.meta.env.VITE_SHOP_H5_HOST}/#/pages/preview/index`
});

onMounted(async () => {
    id.value = router.currentRoute.value.query.pageId || '';
    if (router.currentRoute.value.query.type) {
        pageInfo.previewUrl = getPreviewUrl(id.value, '', storage.get('ZW-SHOPNAME'), false);
    } else {
        pageInfo.previewUrl = `${import.meta.env.VITE_SHOP_H5_HOST}/#/pages/preview/index?pageId=${
            id.value
        }&shopName=${storage.get('ZW-SHOPNAME')}&ZW-PLATFORM-TOKEN=${storage.get(
            'ZW-TOKEN'
        )}&ZW-TENANT-ID=${storage.get('ZW-TENANT-ID')}&ZW-SHOP-ID=${storage.get('ZW-SHOPID')}`;
    }

    if (router.currentRoute.value.query.type == 'preview') {
        getcode(router.currentRoute.value.query.isHomePage, id.value);
    }
    nextTick(() => {
        iframeMessage = new IframeMessage(iframeRef.value.contentWindow, `${import.meta.env.VITE_SHOP_H5_HOST}`);
        listenIframeData();
        saveoredit();
    });
});
/**获取小程序二维码路径 */
const getcode = async (isHomePage, id) => {
    let path = ['', 'pages/tabbar/home', 'pages-activity/dynamic/index', 'pages-cart/paystatus/index'];
    let params = ''; // 参数 类似shopId=16961
    if (isHomePage == 1) {
        params = `shopId=${storage.get('ZW-SHOPID')}`;
    } else if (isHomePage == 2) {
        params = `id=${id}&shopId=${storage.get('ZW-SHOPID')}`;
    } else {
        params = `type=1&id=${id}&shopId=${storage.get('ZW-SHOPID')}`;
    }
    const res = await getMiniAppQrcodeHook(path[JSON.parse(isHomePage)], params, 1, 'qrcode');
    previewUrl.value = res?.data?.url;
};
/**
 * 拖动中
 * @param {*} item
 */
const dragHandler = item => {
    currentDragComponent = item;
    visible.value = true;
    nextTick(() => {
        previewRef.value.scrollTop = centerRef.value.scrollTop;
    });
};

/**
 * 拖动结束
 */
const dragEndHandler = () => {
    visible.value = false;
    nowAbove.status = '';
};

/**
 * 进入目标区域
 */
const dragenterHandler = e => {
    if (e.target.className.startsWith('iframe-mask-item')) return;
    iframeMessage.emit('dragenter');
};

/**
 * 离开目标区域
 */
const dragleaveHandler = e => {
    if (e.relatedTarget.className.startsWith('iframe-mask')) return;
    iframeMessage.emit('dragleave');
    nowAbove.status = '';
};

/**
 * 禁止dragover事件
 * @param {*} e
 */
const dragoverHandler = e => {
    e.preventDefault();
};

/**
 * dragover事件
 * @param {*} e
 * @param {*} index
 */
const dragoverItemHandler = (e, index) => {
    e.preventDefault();
    e.stopPropagation();
    nowAbove.index = index;
    const divObj = maskRefs[index].getBoundingClientRect();
    const nowMarginTop = e.y - divObj.y;
    if (nowMarginTop >= divObj.height / 2) {
        //false代表鼠标在组件下方
        nowAbove.status = false;
    } else {
        //true代表鼠标在组件上方
        nowAbove.status = true;
    }
};
const closePage = () => {
    window.opener = null;
    window.open('', '_self', '');
    window.close();
};
/**
 * 监听被拖拽元素与目标组件相对位置的变化
 */
watch(
    () => nowAbove.status,
    () => {
        const { index, status } = nowAbove;
        if (status !== '') {
            iframeMessage.emit('addMaskOver', { index, status });
        }
    }
);

/**
 * 落入目标区域
 * @param {*} e
 */
const dropHandler = e => {
    e.preventDefault();
    iframeMessage.emit('drop', { title: currentDragComponent.title, name: currentDragComponent.name });
    dragEndHandler();
};
/**
 * 监听iframe高度的变化
 */
const listenIframeData = e => {
    iframeMessage.on('changeIframeHeight', val => {
        totalHeight.value = val;
    });

    iframeMessage.on('changeMaskHeight', val => {
        iframeHeightArr.length = 0;
        iframeHeightArr.push(...val);
        let r = iframeHeightArr.reduce((sum, cur) => {
            return sum + cur;
        }, 0);
        maskHeight.value = r > maskHeight.value ? r + 60 : maskHeight.value;
    });

    iframeMessage.on('passValueToParent', val => {
        name.value = val.name;
        components.value = val.components ? JSON.parse(val.components) : components.value;
        comIndex.value = val.index;
        if (val.name == 'info') {
            form.data = JSON.parse(val.form)[0];
        }
        // 新增/编辑页面，修改页面内容后未保存/发布，点击“退出编辑器”弹出“提示”弹窗。
        if (!isOperate.value) {
            isOperate.value = val.isOperate;
        }
    });
};
const paramSolve = data => {
    data.forEach(item => {
        if (['product', 'seckill', 'groupbuy', 'coupon'].includes(item.options.name)) {
            item.options.imgList = item.options.imgList.map(item => item.id);
        }
    });
};
/**编辑or保存 */
const saveoredit = () => {
    iframeMessage.on('getAllParam', val => {
        let param = JSON.parse(JSON.stringify(val));
        components.value = JSON.parse(val.components);
        param.components = JSON.parse(val.components);
        if (oneSave.value) {
            if (formvalid(param)) {
                paramSolve(param.components);
                if (id.value) {
                    //编辑并发布
                    if (isPreview.value == 4) {
                        request('decorateUpdateServ', { id: id.value, ...param }).then(res => {
                            request('homePubServ', { templateId: id.value, isEnable: 1 }).then(res => {
                                ElMessage.success('发布成功');
                            });
                            oneSave.value = false;
                        });
                    }
                    //编辑
                    if (isPreview.value == 2) {
                        request('decorateUpdateServ', { id: id.value, ...param }).then(res => {
                            ElMessage.success('保存成功');
                            oneSave.value = false;
                        });
                    }
                    //编辑
                    if (isPreview.value == 5) {
                        request('decorateUpdateServ', { id: id.value, ...param }).then(res => {
                            oneSave.value = false;
                            window.open(
                                location.origin +
                                    `/decorate/add?pageId=${id.value}&type=preview&isHomePage=${param.isHomePage}`
                            );
                        });
                    }
                } else {
                    request('decorateServ', param).then(res => {
                        id.value = res.data;
                        oneSave.value = false;
                        if (isPreview.value == 1) {
                            window.open(
                                location.origin +
                                    `/decorate/add?pageId=${id.value}&type=preview&isHomePage=${param.isHomePage}`
                            );
                        } else if (isPreview.value == 3) {
                            request('homePubServ', { templateId: id.value, isEnable: 1 }).then(res => {
                                ElMessage.success('发布成功');
                            });
                        } else {
                            ElMessage.success('保存成功');
                        }
                    });
                }
            }
        }
    });
};
/**表单校验 */
const formvalid = data => {
    for (let key in data) {
        if (!['components', 'pageCode', 'shareImg', 'shareTitle', 'templateDesc'].includes(key)) {
            if (isEmpty(data[key])) {
                ElMessage.warning(`请输入${infotips[key]}`);
                return false;
            }
        }
    }
    // 组件信息校验
    try {
        // 支付结果页,组件可以为空
        if (data.isHomePage == 3 && !data.components.length) {
            throw new Error(1);
        }
        // 除支付结果页，其他拖拽组件不能为空
        if (!data.components.length && data.isHomePage != 3) {
            ElMessage.warning(`请选择组件`);
            throw new Error(2);
        }
        data.components.forEach((item, num) => {
            if (item.options.name == 'images') {
                if (item.options.tabs == 1) {
                    if (!item.options.imgList.length) {
                        alertTips(item);
                    } else {
                        item.options.imgList.map(value => {
                            if (!value.imgurl || isEmpty(value.mutual)) {
                                alertTips(item);
                            }
                            if ([2, 3, 6, 8, 9, 10, 11].includes(value.mutual) && isEmpty(value.id)) {
                                alertTips(item);
                            }
                            if (value.mutual == 12 && isEmpty(value.url)) {
                                alertTips(item);
                            }
                            if (value.mutual == 14 && (isEmpty(value.url) || isEmpty(value.appId))) {
                                alertTips(item);
                            }
                            if (value.mutual == 19 && isEmpty(value.openimg)) {
                                alertTips(item);
                            }
                        });
                    }
                } else if (item.options.tabs == 2) {
                    if (!item.options.imgList.length) {
                        alertTips(item);
                    } else {
                        item.options.imgList.map(value => {
                            if (!value.imgurl || isEmpty(value.mutual)) {
                                alertTips(item);
                            }
                            if ([2, 3, 6, 8, 9, 10, 11].includes(value.mutual) && isEmpty(value.id)) {
                                alertTips(item);
                            }
                            if (value.mutual == 12 && isEmpty(value.url)) {
                                alertTips(item);
                            }
                            if (value.mutual == 14 && (isEmpty(value.url) || isEmpty(value.appId))) {
                                alertTips(item);
                            }
                            if (value.mutual == 19 && isEmpty(value.openimg)) {
                                alertTips(item);
                            }
                        });
                    }
                } else if (item.options.tabs == 3) {
                    if (!item.options.imgList.length) {
                        alertTips(item);
                    } else {
                        item.options.imgList.map(value => {
                            if (!value.imgurl || isEmpty(value.mutual)) {
                                alertTips(item);
                            }
                            if ([2, 3, 6, 8, 9, 10, 11].includes(value.mutual) && isEmpty(value.id)) {
                                alertTips(item);
                            }
                            if (value.mutual == 12 && isEmpty(value.url)) {
                                alertTips(item);
                            }
                            if (value.mutual == 14 && (isEmpty(value.url) || isEmpty(value.appId))) {
                                alertTips(item);
                            }
                            if (value.mutual == 19 && isEmpty(value.openimg)) {
                                alertTips(item);
                            }
                        });
                    }
                } else {
                    if (!item.options.imgList.length) {
                        alertTips(item);
                    } else {
                        item.options.imgList.map(value => {
                            if (!value.imgurl || isEmpty(value.mutual)) {
                                alertTips(item);
                            }
                            if ([2, 3, 6, 8, 9, 10, 11].includes(value.mutual) && isEmpty(value.id)) {
                                alertTips(item);
                            }
                            if (value.mutual == 12 && isEmpty(value.url)) {
                                alertTips(item);
                            }
                            if (value.mutual == 14 && (isEmpty(value.url) || isEmpty(value.appId))) {
                                alertTips(item);
                            }
                            if (value.mutual == 19 && isEmpty(value.openimg)) {
                                alertTips(item);
                            }
                        });
                    }
                }
            } else if (item.options.name == 'product') {
                if (!item.options.imgList.length) {
                    alertTips(item);
                }
                if (item.options.tabs == 2) {
                    if (item.options.imgList.length < 2) {
                        alertTips(item);
                    }
                } else if (item.options.tabs == 3) {
                    if (item.options.imgList.length < 3) {
                        alertTips(item);
                    }
                } else if (item.options.tabs == 4) {
                    if (item.options.imgList.length < 4) {
                        alertTips(item);
                    }
                }
            } else if (item.options.name == 'category') {
                if (!item.options.imgList.length) {
                    alertTips(item);
                } else {
                    item.options.imgList.map(value => {
                        if (!value.imgurl || isEmpty(value.name) || isEmpty(value.mutual)) {
                            alertTips(item);
                        }
                        if ([2, 3, 6, 8, 9, 10, 11].includes(value.mutual) && isEmpty(value.id)) {
                            alertTips(item);
                        }
                        if (value.mutual == 12 && isEmpty(value.url)) {
                            alertTips(item);
                        }
                        if (value.mutual == 14 && (isEmpty(value.url) || isEmpty(value.appId))) {
                            alertTips(item);
                        }
                        if (value.mutual == 19 && isEmpty(value.openimg)) {
                            alertTips(item);
                        }
                    });
                }
            } else if (item.options.name == 'seckill') {
                if (!item.options.imgList.length) {
                    alertTips(item);
                }
            } else if (item.options.name == 'groupbuy') {
                if (!item.options.imgList.length && item.options.addType == 1) {
                    alertTips(item);
                }
                if (!item.options.groupType.length && item.options.addType != 1) {
                    alertTips(item);
                }
            } else if (item.options.name == 'coupon') {
                if (!item.options.imgList.length) {
                    alertTips(item);
                }
            } else if (item.options.name == 'text') {
                for (let key in item.options) {
                    if (['title', 'content'].includes(key)) {
                        if (isEmpty(item.options[key])) {
                            ElMessage.warning(`请完善${item.title}`);
                            iframeMessage.emit('changeOptions', { ...item.options, isValid: true });
                            throw new Error(2);
                        }
                    }
                }
                if (item.options.show) {
                    if (isEmpty(item.options.name) || isEmpty(item.options.mutual)) {
                        alertTips(item);
                    }
                    if ([2, 3, 6, 8, 9, 10, 11].includes(item.options.mutual) && isEmpty(item.options.id)) {
                        alertTips(item);
                    }
                    if (item.options.mutual == 12 && isEmpty(item.options.url)) {
                        alertTips(item);
                    }
                    if (item.options.mutual == 14 && (isEmpty(item.options.url) || isEmpty(item.options.appId))) {
                        alertTips(item);
                    }
                    if (item.options.mutual == 19 && isEmpty(item.options.openimg)) {
                        alertTips(item);
                    }
                }
            } else if (item.options.name == 'wecom') {
                for (let key in item.options) {
                    if (['titleIcon', 'title', 'description', 'btnText', 'qwCode'].includes(key)) {
                        if (isEmpty(item.options[key])) {
                            ElMessage.warning(`请完善${item.title}`);
                            iframeMessage.emit('changeOptions', { ...item.options, isValid: true });
                            throw new Error(2);
                        }
                    }
                }
            }
            if (num == data.components.length - 1) {
                throw new Error(1);
            }
        });
    } catch (e) {
        if (e.message == 1) {
            return true;
        } else {
            return false;
        }
    }
};
const alertTips = item => {
    ElMessage.warning(`请完善${item.title}`);
    let { imgList } = item.options;
    if (imgList) {
        imgList = JSON.stringify(imgList);
        Object.assign(item.options, { imgList });
    }
    iframeMessage.emit('changeOptions', { ...item.options, isValid: true });
    throw new Error(2);
};
const backpage = () => {
    // note：新增/编辑页面，修改页面内容后未保存/发布，点击“退出编辑器”弹出“提示”弹窗。
    if (isOperate.value && !isSave.value) {
        ElemBox.ElMessageBoxPromise(`当前页面部分组件的修改未保存，确定要退出吗？`).then(res => {
            router.go(-1);
        });
    } else {
        router.go(-1);
    }
};
const preview = () => {
    isSave.value = true;
    if (id.value) {
        //编辑并预览
        oneSave.value = true;
        submit(5);
    } else {
        oneSave.value = true;
        //保存并预览
        submit(1);
    }
};
/**发布 */
const publish = () => {
    isSave.value = true;
    if (id.value) {
        //编辑并发布
        oneSave.value = true;
        submit(4);
    } else {
        //保存并发布
        oneSave.value = true;
        submit(3);
    }
};
const changeOptionsHandler = value => {
    iframeMessage.emit('changeOptions', value);
};
const submit = parm => {
    isSave.value = true;
    oneSave.value = true;
    isPreview.value = parm;
    iframeMessage.emit('submit');
};
onBeforeUnmount(() => {
    iframeMessage.destroy();
});
</script>
<style lang="scss">
html,
body {
    overflow: hidden;
}
</style>
<style lang="scss" src="./style.scss" scoped></style>
